package com.cb.exception;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import com.cb.admin.domain.ErrorInfo;
import com.cb.util.JSONUtil;

/**
 * 同意异常捕捉
 * @author Administrator
 *
 */
@ControllerAdvice
public class GlobalExceptionHandler {
	
	//默然返回页面
	public static final String DEFAULT_ERROR_VIEW = "err";
	
	private static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

	/**
	 * 页面错误返回
	 * @param req
	 * @param e
	 * @return
	 * @throws Exception
	 */
	@ExceptionHandler(value = Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ModelAndView mav = new ModelAndView();
        if( "XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {//如果是ajax返回指定格式数据
            logger.info("----------AJAX请求拒绝-------------");
            mav = new ModelAndView();
            FastJsonJsonView view = new FastJsonJsonView();
            ex.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(ex));
            Map<String,Object> map = new HashMap<>();
            String beanString = JSONUtil.returnForbiddenResult();
            map = JSON.parseObject(beanString,Map.class);
            view.setAttributesMap(map);
            mav.setView(view);
            return mav;
            
        } else {//如果是普通请求进行重定向
            logger.info("----------普通请求拒绝-------------");
            mav.addObject("exception", ex);
            mav.addObject("url", request.getRequestURL());
            mav.setViewName(DEFAULT_ERROR_VIEW);
            return mav;
        }
    }

	/**
	 * Json错误返回
	 * @param req
	 * @param e
	 * @return
	 * @throws Exception
	 */
    @ExceptionHandler(value = MyException.class)
    @ResponseBody
    public ErrorInfo<String> jsonErrorHandler(HttpServletRequest req, MyException e) throws Exception {
        ErrorInfo<String> r = new ErrorInfo<>();
        r.setMessage(e.getMessage());
        r.setCode(ErrorInfo.ERROR);
        r.setData("Some Data");
        r.setUrl(req.getRequestURL().toString());
        return r;
    }

}

